/*
** my_showmem.c for showmem in /u/all/muller_b/cu/rendu/piscine/Jour_06
** 
** Made by quentin muller
** Login   <muller_b@epitech.net>
** 
** Started on  Tue Oct 13 14:05:25 2009 quentin muller
** Last update Wed Oct 14 13:15:30 2009 quentin muller
*/
#define FALSE 0

#include <unistd.h>
#include <string.h>

void		my_putchar(char c)
{
  write(1, &c, 1);
}

int		my_putstr(char *str)
{
  int		n;

  n = 0;
  while (str[n] != 0)
    {
      my_putchar(str[n]);
      n++;
    }
  return (FALSE);
}

int		my_strlen(char *str)
{
  int		n;

  n = 0;
  while (str[n] != 0)
    {
      n++;
    }
  return (n);
}

void		set_nbr_base(char *base, char *out, char *adress, int wa)
{
  int		i;
  int		len;

  len = my_strlen(out);
  i = 0;
  while (i < len)
    {
      if (out[i] < 0)
        out[i] *= -1;
      adress[wa + len - i - 1] = '0';
      adress[wa + len - i - 1] = base[out[i]];
      i++;
    }
  return ;
}

int		my_putnbr_base_spec(int nbr, char *base, char *adress, int wa)
{
  int		based;
  char		out[1024];
  int		i;
  int		nbr_b;

  nbr_b = nbr;
  if (base[0] == '\0')
    return (0);
  i = 0;
  based = my_strlen(base);
  while (nbr != 0)
    {
      out[i] = nbr % based;
      nbr /= based;
      i++;
    }
  out[i] = '\0';
  set_nbr_base(base, out, adress, wa);
  return (nbr_b);
}

void		add_adress(char *adress, int n)
{
  adress[n] = adress[n] + 1;
  if (adress[n] == '9' + 1)
    adress[n] = 'a';
  if (adress[n] == 'f' + 1)
    {
      adress[n] = '0';
      add_adress(adress, n - 1);
    }
  return ;
}

int		my_str_isp(char str)
{
  if ((str >= '!' - 1) && (str <= '~'))
    return (1);
  return (0);
}

int		my_showmem(char *str, int size)
{
  int		i;
  int		j;
  static char   adress_cpy[] = "00000000: 0000 0000 0000 0000 0000 0000 0000 0000";
  char		adress[strlen(adress_cpy)];
  static char	base[] = "0123456789abcdef";
  static char	space[] = "  ";
  char		prose[17];
  int		ok_adr;
  int		max = (size < 16 ? size : 16);

  prose[16] = '\0';
  j = 0;
  while ((j < size / 16) || (j == 0 && size < 16))
    {
      strcpy(adress, adress_cpy);
      i = 0;
      ok_adr = 7;
      while (i < max)
        {
          ok_adr +=  2;
          if ((i % 2) == 0)
            ok_adr += 1;
          my_putnbr_base_spec(str[i + j * 16], base, adress, ok_adr);
          if (my_str_isp(str[i + j * 16]))
            prose[i] = str[i + j * 16];
          else
            prose[i] = '.';
          i++;
        }

      my_putstr(adress);
      my_putstr(space);
      my_putstr(prose);
      add_adress(adress, 6);
      my_putchar('\n');
      j++;
    }
  return (0);
}
